import React, { useContext, memo, useMemo } from 'react';
import type { ActionType, ProColumns } from "@ant-design/pro-components";
import { EditableProTable, ProProvider } from "@ant-design/pro-components";
import type { FormInstance } from 'antd';
import switchStatus from './valueType/switchStatus';

/**
 * PC端表格的属性类型
 * @template T - 表格数据类型
 */
export interface PcTableProps<T> {
  /** 表格列配置 */
  columns: ProColumns<T>[];
  /** 表格数据源 */
  dataSource: T[];
  /** 表格加载状态 */
  loading?: boolean;
  /** 表格的ref */
  actionRef?: React.MutableRefObject<ActionType | undefined>;
  /** 表单的ref */
  formRef?: React.MutableRefObject<FormInstance | undefined>;
  /** 可编辑的行key数组 */
  editableKeys?: React.Key[];
  /** 分页配置 */
  pagination: {
    total: number;
    pageSize: number;
    current: number;
    onChange: (page: number, pageSize: number) => void;
  };
  /** 工具栏渲染函数 */
  toolBarRender?: () => React.ReactNode[];
  /** 编辑配置 */
  editable?: {
    type: 'single' | 'multiple';
    editableKeys: React.Key[];
    actionRender: (row: T, config: any, defaultDom: any) => React.ReactNode[];
    onSave: (key: React.Key, row: T) => Promise<void>;
    onCancel: (key: React.Key) => Promise<void>;
  };
  /** 表格大小 */
  size?: 'small' | 'middle' | 'large';
  /** 表格行选择配置 */
  rowSelection?: {
    selectedRowKeys: React.Key[];
    onChange: (selectedRowKeys: React.Key[], selectedRows: T[]) => void;
  };
  /** 表格行点击事件 */
  onRow?: (record: T) => React.HTMLAttributes<HTMLElement>;
  /** 自定义空状态 */
  locale?: {
    emptyText: React.ReactNode;
  };
}

/**
 * PC端表格组件
 * @template T - 表格数据类型
 */
const PcTable = <T extends Record<string, any>>(props: PcTableProps<T>) => {
  const {
    columns,
    dataSource,
    loading,
    actionRef,
    formRef,
    editableKeys,
    pagination,
    toolBarRender,
    editable,
    size = 'middle',
    rowSelection,
    onRow,
    locale,
  } = props;

  const values = useContext(ProProvider);

  // 缓存 Provider value
  const providerValue = useMemo(() => ({
    ...values,
    valueTypeMap: {
      switchStatus
    },
  }), [values]);

  // 缓存表格配置
  const tableConfig = useMemo(() => ({
    rowKey: "id",
    actionRef,
    formRef,
    columns,
    value: dataSource,
    loading,
    pagination,
    search: false,
    toolBarRender,
    scroll: { x: 'max-content' },
    editable,
    size,
    rowSelection,
    onRow,
    locale,
  }), [
    actionRef,
    formRef,
    columns,
    dataSource,
    loading,
    pagination,
    toolBarRender,
    editable,
    size,
    rowSelection,
    onRow,
    locale,
  ]);

  return (
    <ProProvider.Provider value={providerValue}>
      <EditableProTable<T, any> {...tableConfig} />
    </ProProvider.Provider>
  );
};

// 使用 memo 包裹组件，避免不必要的重渲染
export default memo(PcTable) as typeof PcTable; 